package com.cn.yugan.Activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ListView;

import com.cn.yugan.Engine.Http.GetList;
import com.cn.yugan.Engine.Json.CommentItemJsonObj;
import com.cn.yugan.Engine.Json.CommentResponsJsonObj;
import com.cn.yugan.Engine.Beans.CommentFloor;
import com.cn.yugan.Engine.Beans.CommentObj;
import com.cn.yugan.mobile.R;
import com.cn.yugan.Utils.CommentListView.CommentListViewAdapter;
import com.cn.yugan.Utils.LogUtils;
import com.cn.yugan.Utils.ToastUtils;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.apache.http.Header;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommentActivity extends AppCompatActivity {

    /**
     * 评论区返回的json串内容
     */
    private String aid = "";
    private int page = 1;
    private CommentObj commentObj = new CommentObj();
    private String json = "{\"success\": true,\"data\": {},\"count\": \"0\",\"root\": []}";
    // 分割
    private PullToRefreshListView lvTest;
    private CommentListViewAdapter adapter;

    /**
     * 每层楼都有对应的点击监听,不要弄混了
     */
    private Map<CommentFloor, View.OnClickListener> hideBtnOnclickMap = new HashMap<CommentFloor, View.OnClickListener>();
    /**
     * 当前显示的item
     */
    private int curItemIndex = 0;

    public static CommentActivity instance = null;

    /**
     * 传来的cid
     */
    private int cid = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment);
        instance = this;

        init();
        initViews();
        getdatainnet(1);

    }

    private void init() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("评论");
        actionBar.setDisplayHomeAsUpEnabled(true);

        Intent intent = getIntent();
        aid = intent.getStringExtra("aid");
        cid = intent.getIntExtra("cid", 0);

        LogUtils.e("aid==" + aid);
        LogUtils.e("cid==" + cid);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.action_comment_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                break;
            case R.id.action1_recomment:
                Intent intent = new Intent(CommentActivity.this, ReCommentActivity.class);
                //传输的数据
                intent.putExtra("aid", aid);
                startActivity(intent);
                break;
        }
        return true;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.action_comment, menu);
    }


    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()) {
            case R.id.action_comment_getcomment:
                ToastUtils.show(this, commentObj.getItem(menuInfo.position - 1).floor + "");
                int floor = commentObj.getItem(menuInfo.position - 1).floor;
                Intent intent = new Intent(CommentActivity.this, ReCommentActivity.class);
                intent.putExtra("floor", floor);
                intent.putExtra("aid", aid);
                startActivity(intent);
                break;
            case R.id.action_comment_message:
                break;
            case R.id.action_comment_userinfo:
                break;
            case R.id.action_comment_tipoff:
                break;
            case R.id.action_comment_copy:
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clipData = ClipData.newHtmlText("鱼干", "", commentObj.getItem(menuInfo.position - 1).content + "");
                cm.setPrimaryClip(clipData);
                ToastUtils.show(this, "复制成功");
                break;
        }
        return super.onContextItemSelected(item);
    }

    /**
     * 初始化控件
     */
    private void initViews() {
        getData();
        lvTest = (PullToRefreshListView) findViewById(R.id.listView1);
        lvTest.setMode(PullToRefreshBase.Mode.BOTH);
        lvTest.setOnRefreshListener(new OnRefreshListener());
        ILoadingLayout startLabels = lvTest
                .getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("下拉我帮你刷新(*^__^*) ");// 刚下拉时，显示的提示    
        startLabels.setRefreshingLabel("鱼干娘帮你刷新中...");// 刷新时    
        startLabels.setReleaseLabel("放开我啊，臭流氓((‵□′)) ");// 下来达到一定距离时，显示的提示  

        ILoadingLayout endLabels = lvTest.getLoadingLayoutProxy(
                false, true);
        endLabels.setPullLabel("上拉我帮你加载(*^__^*) ");// 刚下拉时，显示的提示    
        endLabels.setRefreshingLabel("鱼干娘寻找中...");// 刷新时    
        endLabels.setReleaseLabel("放开我啊，臭流氓((‵□′)) ");// 下来达到一定距离时，显示的提示
        adapter = new CommentListViewAdapter(this, commentObj, hideBtnOnclickMap);
        lvTest.setAdapter(adapter);
        registerForContextMenu(lvTest.getRefreshableView());

    }


    class HideBtnOnclickListener implements View.OnClickListener {
        CommentFloor floor;

        public HideBtnOnclickListener(CommentFloor floor) {

            this.floor = floor;
        }

        @Override
        public void onClick(View v) {
            floor.flagHidenRepeat = !floor.flagHidenRepeat;
            if (floor.flagHidenRepeat == true) {
                // int curShowItemIndex = curItemIndex;
                // 点击后执行的是隐藏操作-list变短,需要自动跟踪到刚才操作的楼层
                adapter.notifyDataSetChanged();

                //lvTest(curShowItemIndex - floor.getHideSum());
            } else {
                // 点击后执行的是展开操作-展开后不需要移动list
                adapter.notifyDataSetChanged();
            }
        }
    }

    public void getData() {

        Gson gson = new Gson();
        LogUtils.d(json);
        CommentResponsJsonObj commentJsons = gson.fromJson(json, CommentResponsJsonObj.class);
        LogUtils.d(commentJsons.count + "");
        List<String> commentStrList = commentJsons.getCommentStrList();
        System.out.println("解析成功-没有报错~");
        System.out.println("尝试打印每栋楼的一楼楼层号:");
        System.out.println("list长度:" + commentStrList.size());
        for (String cId : commentStrList) {
            System.out.println("格式化:" + cId);
            // 造楼
            CommentItemJsonObj item = commentJsons.data.get(cId);
            CommentFloor floor = null;
            if (item != null) {
                if (item.author.equals("")) {
                    item.author = "未知用户";
                    item.content = "该评论已被删除";
                }
                floor = new CommentFloor();
                floor.addHightFloor(item);
            }
            while (floor != null) {
                CommentItemJsonObj hightFloor = floor.getHightFloor();
                if (hightFloor != null && hightFloor.replycid != 0
                        && hightFloor.replycid != 0.0) {
                    // 寻找下一个,添加到floor中
                    // 获取引用的楼层对象
                    CommentItemJsonObj moreHightFloor = commentJsons.data
                            .get("yu" + hightFloor.replycid);
                    if (moreHightFloor.author.equals("")) {
                        moreHightFloor.author = "未知用户";
                        moreHightFloor.content = "该评论已被删除";
                    }
                    // 将楼层对象加入floor中
                    floor.addHightFloor(moreHightFloor);
                } else {
                    break;
                }
            }
            // 计算一下每楼的楼号和隐藏了多少楼
            // floor.setFloorNums();
            commentObj.addOneF(floor);
            if (floor.repeatIndex != 0) {
                View.OnClickListener hideBtnListener = new HideBtnOnclickListener(
                        floor);
                hideBtnOnclickMap.put(floor, hideBtnListener);
            }
        }
    }

    public void getdatainnet(final int page) {
        String url = getString(R.string.serverurl) + getString(R.string.articlecomment);
        LogUtils.d("aid====>" + aid);
        LogUtils.d("page====>" + page);
        GetList.CommentListAsyncHttpClient(this, url, aid, page, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                try {
                    json = new String(bytes, "UTF-8");
                    LogUtils.d(json);
                    if (page == 1) {
                        commentObj = new CommentObj();
                        hideBtnOnclickMap = new HashMap<CommentFloor, View.OnClickListener>();
                    }
                    getData();
                    lvTest.onRefreshComplete();
                    adapter.refresh(hideBtnOnclickMap, commentObj);
                    if (cid != 0) {
                        int flag = 0;
                        for (int j = 0; j < adapter.getCount(); j++) {
                            if (((CommentItemJsonObj) adapter.getItem(j)).cid == cid) {
                                lvTest.getRefreshableView().setSelection(j+1);
                               // ToastUtils.show(CommentActivity.this, j+1 + "");
                                //动画效果延迟执行
                                Handler handler = new Handler();
                                final int finalJ = j+1;
                                handler.postDelayed(new Runnable() {
                                    public void run() {
                                        Animation shake = AnimationUtils.loadAnimation(CommentActivity.this, R.anim.shake);
                                        ListView mlistview = lvTest.getRefreshableView();
                                        LogUtils.e("firstvisiblePosition====>" + mlistview.getFirstVisiblePosition());
                                        LogUtils.e("position====>" + finalJ);
                                        mlistview.getChildAt(finalJ - mlistview.getFirstVisiblePosition()).startAnimation(shake);
                                    }
                                }, 500);

                                flag = 1;
                                break;
                            }
                        }
                        if (flag == 0) {
                            getdatainnet(page + 1);
                        }
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                ToastUtils.show(CommentActivity.this, "服务器错误");
                lvTest.onRefreshComplete();
            }
        });
    }

    private class OnRefreshListener implements PullToRefreshBase.OnRefreshListener<ListView> {
        @Override
        public void onRefresh(final PullToRefreshBase<ListView> refreshView) {
            if (lvTest.isHeaderShown()) {
                String label = DateUtils.formatDateTime(CommentActivity.this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                refreshView.getLoadingLayoutProxy()
                        .setLastUpdatedLabel(label);
                //下拉加载逻辑
                getdatainnet(1);
            } else if (lvTest.isFooterShown()) {
                //上拉加载逻辑
                page++;
                getdatainnet(page);
            }
        }

    }

    public void refreshdata() {
        getdatainnet(1);
        adapter.notifyDataSetInvalidated();
    }

}
